package com.shihan.rabbitmq.producer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BasicProperties;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.shihan.rabbitmq.utils.ConnUtil;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description 持久化处理 Queue、Exchange、Message，避免异常情况下的消息丢失
 * @Author shihan
 * @Date 2021/1/2 16:11
 * @Version 1.0
 */
public class PersistentStorage {

    public static final String EXCHANGE_NAME_DIRECT_P = "exc.direct.persistent.name";

    public static final String QUEUE_NAME_P = "queue.persistent.name";

    public static final String BINDING_KEY_P = "direct.persistent.key";

    public static void main(String[] args) throws URISyntaxException, IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException {
        Channel channel = ConnUtil.getChannel();

        // 持久化 Exchange、Queue
        channel.exchangeDeclare(EXCHANGE_NAME_DIRECT_P, BuiltinExchangeType.DIRECT, true);
        channel.queueDeclare(QUEUE_NAME_P, true, false, false, null);

        channel.queueBind(QUEUE_NAME_P,EXCHANGE_NAME_DIRECT_P,BINDING_KEY_P);

        // 发送的消息持久化
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
                // deliveryMode 为 2，表示为持久化消息
                .deliveryMode(2)
                .build();

        channel.basicPublish(
                EXCHANGE_NAME_DIRECT_P,
                BINDING_KEY_P,
                basicProperties,
                "目标发送的 Msg 信息！".getBytes("utf-8")
        );

        ConnUtil.closeConn();
    }

}
